package com.pine.dbant.plugin.sqlite.function;

import com.pine.dbant.common.jdbc.JdbcUtils;
import com.pine.dbant.common.model.EditorDbKey;
import com.pine.dbant.common.plugin.meta.JdbcMetadataAnalysisConfig;
import com.pine.dbant.common.plugin.meta.QueryMetadataParam;
import com.pine.dbant.common.plugin.meta.function.jdbc.ColumnsEditorKeyFunction;
import com.pine.sunflower.core.utils.Strings;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xiaoyuan
 * @create 2023/3/9 10:20
 **/
public class SqliteColumnsEditorKeyFunction extends ColumnsEditorKeyFunction {

    public SqliteColumnsEditorKeyFunction(String type) {
        super(type);
    }

    @Override
    public List<EditorDbKey.Column> doQuery(JdbcMetadataAnalysisConfig metadataAnalysisConfig, QueryMetadataParam queryMetadataParam) {
        String catalog = queryMetadataParam.getConfiguration().getNecessaryValue("catalog");
        String tableName = queryMetadataParam.getConfiguration().getNecessaryValue("tableName");
        String sql = Strings.format("PRAGMA table_info({})", tableName);
        List<Map<String, Object>> columnsResult = JdbcUtils.getSqlRunner(metadataAnalysisConfig.getConnection()).queryList(sql);
        Object temp;
        EditorDbKey.Column column;
        List<EditorDbKey.Column> result = new ArrayList<>();
        for (Map<String, Object> map : columnsResult) {
            column = new EditorDbKey.Column();
            temp = map.get("name");
            if (temp != null) {
                column.setColumnName(String.valueOf(temp));
            }
            result.add(column);
        }
        return result;
    }
}
